#include <stdio.h>
#include <stdlib.h>

struct ListNode{
	int val;
	struct ListNode* next;
};

void setList(struct ListNode* head, int *num)
{
	struct ListNode* new, *p;
	int i, len;
	len = sizeof(num)/sizeof(int);
	p = head;
	for(i = 0; i < len; i++)
	{
		new = (struct ListNode*)malloc(sizeof(struct ListNode));
		if(new == NULL)
		{
			printf("new malloc fail\n");
			return;
		}
		new->next = p->next;
		p->next = new;
		p->val = num[i];
		p = p->next;
	}
}

void print(struct ListNode* head)
{
	struct ListNode* p;
	for(p = head; p != NULL; p = p->next)
	{
		printf("[%d]", p->val);
	}
	printf("\n");
}

struct ListNode* deleteDuplicates(struct ListNode* head) {
	if(head == NULL || head->next == NULL)
		return head;
	struct ListNode* pPre, *pCur, *pTmp;
	pTmp = pPre = pCur = head;
	pCur = pCur->next;

	while(pCur != NULL)
	{
		if(pPre->val == pCur->val)
		{
			for(;;)
			{
				pPre->next = pCur->next;
				free(pCur);
				pCur = pPre->next;
				if(pCur == NULL)
					break;
				if(pPre->val != pCur->val)
					break;
			}
			if(pPre == head)
			{
				head = head->next;
				free(pPre);
				pTmp = pPre;
				pPre = head;
				if(head == NULL)
					return head;
			}
			else
			{
				pTmp->next = pCur;
				free(pPre);
				pPre = pCur;
				if(pCur == NULL)
					return head;
			}
			
			if(pPre == pCur)
				pCur = pCur->next;
		}
		else
		{
			pTmp = pPre;
			pPre = pCur;
			pCur = pCur->next;
		}
	}
	return head;

}

void main(void)
{
	struct ListNode* head;
	int num[] = {1,3,3,4,5};
	int val = 1;
	head = (struct ListNode*)malloc(sizeof(struct ListNode));
	head->next = NULL;
	head->val = num[0];
	setList(head, &num[1]);
	print(head);
}

